<template>
  <div class="add-scheme">
    <el-form
      :rules="rules"
      ref="ruleForm"
      :model="dataForm"
      label-width="130px"
      class="dialog"
      autocomplete="off"
    >
      <el-row align="center">
        <el-col :span="12" :offset="6" style="position:relative">
          <el-form-item label="共享方案组编号" prop="groupNo" label-width="130px">
            <el-input
              v-model="dataForm.groupNo"
              placeholder="请输入共享方案组编号"
              clearable
              :disabled="disabledGroupNo"
            ></el-input>
          </el-form-item>
          <p
            style="color:#F56C6C;margin-left:130px;margin-bottom:20px;font-size:12px;position:absolute;left:0;top:45px;"
            v-if="validteGroupNo"
          >该编号已存在,请重新输入</p>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="6" style="position:relative">
          <el-form-item label="共享方案组名称" prop="name" label-width="130px">
            <el-input v-model="dataForm.name" placeholder="请输入共享方案组名称" clearable></el-input>
          </el-form-item>
          <p
            style="color:#F56C6C;margin-left:130px;margin-bottom:20px;font-size:12px;position:absolute;left:0;top:45px;"
            v-if="validateName"
          >该名称已存在,请重新输入</p>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="6">
          <el-form-item label="共享方案名称" label-width="130px">
            <el-select
              v-model="dataForm.shareSchemeCode"
              placeholder="请选择共享方案名称"
              clearable
              style="width:100%"
              @change="getOptions"
            >
              <el-option
                v-for="(item, index) in shareSchemeTypeList"
                :key="index"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <el-row>
        <el-col :span="12" :offset="6">
          <el-form-item label class="search-name">
            <el-input v-model="searchVal" placeholder="请输入名称搜索" clearable>
              <el-button slot="append" icon="el-icon-search" @click="searchUserIsAdd()"></el-button>
            </el-input>
          </el-form-item>
          <p style="color:red;margin-bottom:10px;margin-left:120px;">{{prompt}}</p>
        </el-col>
      </el-row>-->
      <el-row>
        <el-col :span="12" :offset="6">
          <table
            cellspacing="1"
            cellpadding="1"
            class="card_discount"
            :show-overflow-tooltip="true"
            style="margin-bottom: 20px"
          >
            <thead>
              <th>编号</th>
              <th style="border-right:1px solid #fff;border-left:1px solid #fff">名称</th>
              <th style="min-width: 60px;">操作</th>
            </thead>
            <tbody>
              <tr colspan="3" class="search-box" ref="tab">
                <div class="flex search-add" :style="{width:+ w +'px'}">
                  <el-select
                    v-model="value"
                    placeholder="请输入编号或者名称搜索"
                    :style="{width:+ w +'px'}"
                    @change="selectSearch"
                    :disabled="isDisabled"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                </div>
              </tr>
              <tr v-for="(item,index) in addList" :key="item.id">
                <td>{{item.code}}</td>
                <td>{{item.name}}</td>
                <td @click="dels(index)">
                  <span class="grid_del_container">
                    <i class="el-icon-delete"></i>
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
          <!--         <el-pagination
            align="right"
            style="padding-top: 20px;margin-bottom:100px;"
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageData.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageData.size"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper"
          ></el-pagination>-->
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="23">
          <el-form-item prop="remark" label="备注">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入备注"
              v-model="dataForm.remark"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item align="center" style="margin-top:30px;margin-bottom:100px;">
        <el-button type="primary" @click="onSave" :disabled="isDabled">确认</el-button>
        <el-button style="margin-right:100px;" type="info" @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      :title="'请选择'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      id="PurchaseDetail"
      width="60%"
      @close="handleClose"
    >
      <el-form :inline="true" :model="queryForm">
        <el-form-item>
          <el-input v-model="queryForm.name" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="searchDialogList" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        element-loading-text="拼命加载中..."
        v-loading="dataListLoading"
        :data="selectList"
        ref="multipleTable"
        border
        style="width: 100%"
        @selection-change="selectionChangeHandle"
        @select="selectChange"
        @select-all="selectAllChange"
        empty-text="没有查询到数据!"
      >
        <el-table-column align="center" type="selection" width="80px"></el-table-column>
        <el-table-column align="center" prop="code" label="编号" min-width="100px" v-if="isShowCode"></el-table-column>
        <el-table-column align="center" prop="name" label="名称" min-width="100px"></el-table-column>
      </el-table>

      <el-pagination
        align="right"
        style="padding-top: 20px;"
        @size-change="sizeChangeHandleDialog"
        @current-change="currentChangeHandleDialog"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPageDialog"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" type="info">取消</el-button>
        <el-button type="primary" @click="Sureadd">确定添加</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  watch: {
    tableData (val) {
      this.dealData()
    },
    'dataForm.shareSchemeCode' (curVal, oldVal) {
      if (this.type === 'edit' && curVal && !oldVal) {
        setTimeout(() => {
          this.selectType()
        }, 2000)
      }
    },
    visible (val) {
      if (val) {
        this.getDailog(this.needData, this.canPage)
      } else {
        this.selectList = []
        this.queryForm.name = ''
        this.totalPageDialog = 0
        this.pageIndex = 1
      }
    }
  },
  data () {
    var names = (rule, value, callback) => {
      var data = {
        groupNo: this.dataForm.groupNo
      }
      if (value == '') {
        callback(new Error('共享方案组编号不允许为空'))
      } else if (value && !this.noRepeat) {
        this.$http
          .post(
            `/${this.$const.PREFIX.AUTHORITY}/shareSchemeGroup/checkUnique`,
            data
          )
          .then(res => {
            if (res.result) {
              this.noRepeat = res.data
              if (this.noRepeat == false) {
                // res.data.data [true]有重复/【false】无重复
                callback(new Error('该共享方案组编号已存在,请重新输入'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          })
      } else {
        callback()
      }
    }
    return {
      noRepeat: false,
      disabledGroupNo: false,
      validateName: false,
      validteGroupNo: false,
      isDisabled: true,
      dataForm: {
        remark: '',
        groupNo: '',
        name: '',
        shareSchemeCode: ''
      },
      isShowCode: true,
      visible: false,
      dataList: [],
      pageSize: 10,
      pageIndex: 1,
      totalPageDialog: 1,
      dataListLoading: false,
      queryForm: {
        name: ''
      },
      type: '',
      id: '',
      shareSchemeTypeList: [],
      rules: {
        groupNo: [
          { validator: names, required: true, trigger: 'blur' },
          { min: 2, max: 64, message: '长度不可超过64个字符', trigger: 'blur' }
        ],
        name: [
          {
            required: true,
            message: '共享方案组名称不允许为空',
            trigger: 'blur'
          },
          { min: 2, max: 64, message: '长度不可超过64个字符', trigger: 'blur' }
        ],
        remark: [
          {
            min: 2,
            max: 255,
            message: '长度不可超过255个字符',
            trigger: 'blur'
          }
        ]
      },
      pageData: {
        size: 10,
        page: 1
      },
      totalPage: 1,
      value: '',
      searchVal: '',
      searchValSelect: '',
      searchList: [],
      addList: [],
      options: [],
      selectList: [],
      tableData: [],
      prompt: '',
      delDataList: [],
      canPage: '',
      needData: {},
      w: '400',
      dataListSelections: [], // 弹窗table多选数据
      code: '',
      codeType: '',
      isClear: false,
      isDabled: false,
      dealResult: [],
      isClickSearch: false,
      cancelSelectList: []
    }
  },
  mounted () {
    this.getConfig()
    let id = this.$route.params.id
    if (id === 'new') {
      this.type = 'save'
    } else {
      this.code = id
      this.type = 'edit'
      this.disabledGroupNo = true
      this.getEditInfo()
    }
    this.w = this.$refs.tab.offsetWidth
    window.onresize = () => {
      this.w = this.$refs.tab.offsetWidth
    }
  },
  methods: {
    getEditInfo () {
      this.$http
        .post(
          `/${this.$const.PREFIX.AUTHORITY}/shareSchemeGroup/findShareSchemeGroupDetail`,
          { code: this.code }
        )
        .then(res => {
          if (res.result) {
            var data = res.data
            this.dataForm.groupNo = data.groupNo
            this.dataForm.name = data.name
            this.dataForm.shareSchemeCode = data.shareSchemeCode
            this.isDisabled = false
            var list = data.groupProductList
            var newArr = []
            for (var i in list) {
              newArr.push({
                code: list[i].objectNo,
                name: list[i].name,
                objectCode: list[i].objectCode
              })
            }
            this.addList = newArr
            this.dataForm.remark = data.remark
          }
        })
    },
    dealData () {
      var newArr = []
      var arr = this.tableData
      for (var k = 0; k < arr.length; k += 10) {
        newArr.push(arr.slice(k, k + 10))
      }
      this.delDataList = newArr
      this.addList = this.delDataList[0]
      this.totalPage = arr.length
    },
    getConfig () {
      this.$http
        .post(
          `/${this.$const.PREFIX.AUTHORITY}/shareScheme/listShareScheme`,
          {}
        )
        .then(res => {
          if (res.result) {
            this.shareSchemeTypeList = res.data
          }
        })
    },
    // 检测共享方案编号唯一性
    checkOnly (index) {
      if (this.dataForm.name == '' && this.dataForm.groupNo == '') {
        return
      }
      var data = {}
      if (index == 1) {
        data = {
          groupNo: this.dataForm.groupNo
        }
      } else {
        data = {
          name: this.dataForm.name
        }
      }
      this.$http
        .post(
          `/${this.$const.PREFIX.AUTHORITY}/shareSchemeGroup/checkUnique`,
          data
        )
        .then(res => {
          if (res.result) {
            if (res.data) {
              if (index == 1) {
                this.validteGroupNo = false
              } else {
                this.validateName = false
              }
            } else {
              if (index == 1) {
                this.validteGroupNo = true
              } else {
                this.validateName = true
              }
            }
          }
        })
    },
    search (type) {
      if (type === 'default') {
        var selectList1 = this.selectList
        var dealResult1 = []
        for (var x in this.addList) {
          for (var n in selectList1) {
            if (selectList1[n].code == this.addList[x].code) {
              dealResult1.push(selectList1[n])
            }
          }
        }
        if (this.visible) {
          setTimeout(() => {
            dealResult1.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, true)
            }, 300)
          })
        }
        this.dealResult = dealResult1
      } else {
        if (this.isClickSearch) {
          this.visible = true
        }
        if (this.type == 'edit') {
          var selectList = this.selectList
          var dealResult = []
          for (var y in this.addList) {
            for (var k in selectList) {
              if (selectList[k].code == this.addList[y].code) {
                dealResult.push(selectList[k])
              }
            }
          }
          setTimeout(() => {
            dealResult.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, true)
            })
          }, 300)
          this.dealResult = dealResult
        }
      }
    },
    onSave () {
      var list = this.addList
      var proList = []
      for (var k in list) {
        proList.push({
          objectNo: list[k].code,
          name: list[k].name,
          objectCode: list[k].objectCode
        })
      }
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          let data = {
            operateType: this.type,
            shareSchemeGroup: {
              groupNo: this.dataForm.groupNo,
              name: this.dataForm.name,
              shareSchemeCode: this.dataForm.shareSchemeCode,
              remark: this.dataForm.remark
            },
            proList: proList
          }
          if (this.code) {
            data.shareSchemeGroup['code'] = this.code
          }
          this.$http
            .post(
              `/${this.$const.PREFIX.AUTHORITY}/shareSchemeGroup/operationData`,
              data
            )
            .then(res => {
              if (res.result) {
                this.isDabled = true
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.$router.push('/systemSettings/sharePlan/list')
              } else {
                this.isDabled = false
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              this.$message.error(err)
            })
        }
      })
    },
    onCancel () {
      this.$router.push('/systemSettings/sharePlan/list')
    },
    sizeChangeHandle (val) {
      this.pageData.size = val
    },
    currentChangeHandle (val) {
      this.pageData.page = val
      var list = this.delDataList
      this.addList = list[val - 1]
    },
    sizeChangeHandleDialog (val) {
      this.pageSize = val
      this.getDailog(this.needData, this.canPage)
      var selectList = this.selectList
      var dealResult = []
      for (var y in this.addList) {
        for (var k in selectList) {
          if (selectList[k].code == this.addList[y].code) {
            dealResult.push(selectList[k])
          }
        }
      }

      dealResult.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      })
      this.dealResult = dealResult
    },
    currentChangeHandleDialog (val) {
      this.pageIndex = val
      this.getDailog(this.needData, this.canPage)
    },
    selectChange (selection, row) {
      let selected = selection.length && selection.indexOf(row) !== -1
      if (!selected) {
        this.cancelSelectList.push(row)
      } else {
        let index = this.cancelSelectList.indexOf(row)
        this.cancelSelectList.splice(index, 1)
      }
    },
    selectAllChange (selection) {
      if (selection.length === 0) {
        for (let i = 0; i < this.selectList.length; i++) {
          let index = this.cancelSelectList.findIndex(
            item => item.code === this.selectList[i].code
          )
          if (index === -1) {
            this.cancelSelectList.push(this.selectList[i])
          }
        }
      }
    },
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    Sureadd () {
      this.value = ''
      var data = this.dataListSelections
      var len = data.length
      for (var i = 0; i < len; i++) {
        var code = data[i].code
        var index = this.addList.findIndex(item => item.code === code)
        if (index == -1) {
          this.addList.push({
            code: code,
            name: data[i].name,
            objectCode: data[i].objectCode
          })
        }
      }
      var cancelList = this.cancelSelectList
      var cancelLen = cancelList.length
      for (var j = 0; j < cancelLen; j++) {
        var index1 = this.addList.findIndex(
          item => item.code === cancelList[j].code
        )
        if (index1 !== -1) {
          this.addList.splice(index1, 1)
        }
      }
      this.visible = false
      this.cancelSelectList = []
    },
    handleClose () {},
    selectSearch () {
      let index = this.addList.findIndex(item => item.code === this.value)
      if (index === -1) {
        let labelIndex = this.options.findIndex(
          item => item.value === this.value
        )
        let name = this.options[labelIndex].label
        let objectCode = this.options[labelIndex].objectCode
        this.addList.push({
          code: this.value,
          name: name,
          objectCode: objectCode
        })
      }
    },
    dels (index) {
      this.addList.splice(index, 1)
    },
    // 精准搜索
    searchUserIsAdd () {
      var index = this.addList.findIndex(item => item.name === this.searchVal)
      if (index === -1) {
        this.prompt = '没有添加此数据'
      } else {
        this.prompt = '已添加此数据'
      }
    },
    getOptions () {
      this.addList = []
      this.value = ''
      this.selectType()
    },
    selectType () {
      this.isClickSearch = true
      let shareSchemeCode = this.dataForm.shareSchemeCode
      let type = ''
      if (shareSchemeCode) {
        let index = this.shareSchemeTypeList.findIndex(
          item => item.code === shareSchemeCode
        )
        type = this.shareSchemeTypeList[index].shareSchemeType
      } else {
        return
      }
      this.isDisabled = false
      // this.addList = []
      this.value = ''
      this.options = []
      // var type = this.dataForm.shareSchemeCode;
      var list = ''
      var canPage = ''
      var data = {}
      var dataPage = {}
      var code = ''
      if (type == 'area') {
        this.isShowCode = true
        // 区域
        list = 'mareas/list '
        canPage = 'mareas/page'
        dataPage = {}
        code = 'areaNo'
      } else if (type == 'organization') {
        // 组织机构
        list = 'morganizations/list'
        canPage = 'morganizations/page'
        this.isShowCode = false
        dataPage = {}
        code = 'organizationNo'
      } else if (type == 'warehouse') {
        // 仓库
        this.isShowCode = true
        list = 'mwarehouses/list'
        canPage = 'mwarehouses/page'
        dataPage = {}
        code = 'warehouseNo'
      } else if (type == 'vendor_classes') {
        // 供应商分类
        this.isShowCode = true
        list = 'mvendorclasses/list'
        canPage = 'mvendorclasses/page'
        data = {
          type: 0
        }
        dataPage = {
          type: 0
        }
        code = 'classesNo'
      } else if (type == 'vendors') {
        // 供应商信息
        this.isShowCode = true
        list = 'mvendors/list'
        canPage = 'mvendors/page'
        data = {
          type: 0
        }
        dataPage = {
          type: 0
        }
        code = 'itemNo'
      } else if (type == 'direct_store') {
        // 直营店
        this.isShowCode = true
        list = 'customers/list'
        canPage = 'customers/page'
        data = {
          type: 0
        }
        dataPage = {
          type: 0
        }
        code = 'storeNo'
      } else if (type == 'agent_store ') {
        // 代理商门店
        this.isShowCode = true
        list = 'customers/list'
        canPage = 'customers/page'
        data = {
          type: 1
        }
        dataPage = {
          type: 1
        }
        code = 'storeNo'
      } else if (type == 'product_classes') {
        // 商品分类
        this.isShowCode = true
        list = 'mproductclasses/list'
        canPage = 'mproductclasses/page'
        data = {
          itemType: 0
        }
        dataPage = {
          itemType: 0
        }
        code = 'itemNo'
      } else if (type == 'product_series') {
        // 商品系列
        this.isShowCode = true
        list = 'mproductclasses/list'
        canPage = 'mproductclasses/page'
        data = {
          itemType: 1
        }
        dataPage = {
          itemType: 1
        }
        code = 'itemNo'
      } else if (type == 'product_brand') {
        // 商品品牌
        this.isShowCode = true
        list = 'mproductbrandtaste/list'
        canPage = 'mproductbrandtaste/page'
        data = {
          itemType: 0
        }
        dataPage = {
          itemType: 0
        }
        code = 'itemNo'
      } else if (type == 'product_taste') {
        // 商品味道
        this.isShowCode = true
        list = 'mproductbrandtaste/list'
        canPage = 'mproductbrandtaste/page'
        data = {
          itemType: 0
        }
        dataPage = {
          itemType: 0
        }
        code = 'itemNo'
      } else if (type == 'products') {
        // 商品主信息
        this.isShowCode = false
        list = 'mproductdto/list'
        canPage = 'mproductdto/page'
        dataPage = {}
        code = 'productNo'
      } else if (type == 'product_taste') {
        // 子商品信息
        this.isShowCode = true
        list = 'mproductsublist/list'
        canPage = 'mproductsublist/page'
        dataPage = {}
        code = 'productNo'
      }
      this.canPage = canPage
      this.needData = dataPage
      this.codeType = code
      this.getSelectData(data, list)
      this.getDailog(dataPage, canPage)
      this.value = ''
    },
    getSelectData (data, url) {
      this.$http
        .post(`/${this.$const.PREFIX.MAINDATA}/${url}`, data)
        .then(res => {
          if (res.result) {
            let newArr = []
            var data = res.data
            for (var k in data) {
              newArr.push({
                value: data[k][this.codeType],
                label: data[k].name,
                objectCode: data[k].code
              })
            }
            this.options = newArr
          }
        })
    },
    searchDialogList () {
      this.pageIndex = 1
      this.getDailog(this.needData, this.canPage)
    },
    getDailog (data, url) {
      let param = data
      this.queryForm.name = this.queryForm.name && this.queryForm.name.trim()
      if (this.queryForm.name) {
        param = Object.assign({}, data, {
          name: this.queryForm.name
        })
      }
      param = Object.assign(param, {
        current: this.pageIndex,
        size: this.pageSize
      })
      this.$http
        .post(`/${this.$const.PREFIX.MAINDATA}/${url}`, param)
        .then(res => {
          if (res.result) {
            var result = res.data.records
            if (result.length > 0) {
              var newArr = []
              for (var i in result) {
                newArr.push({
                  code: result[i][this.codeType],
                  name: result[i].name,
                  objectCode: result[i].code
                })
              }
              this.selectList = newArr
              this.totalPageDialog = res.data.total
              this.isClickSearch = true
              this.search('default')
            } else {
              this.selectList = []
              this.totalPageDialog = 0
              this.isClickSearch = true
            }
          }
          // eslint-disable-next-line handle-callback-err
        }).catch(error => {
          this.isClickSearch = true
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.add-scheme {
  background: #fff;
  padding: 20px;
}
.card_discount {
  background: #e2e4e4;
  table-layout: fixed;
  width: 100%;
  color: #606266;
}
.card_discount > thead {
  background: #6786b8;
  color: #fff;
  text-align: center;
}
.card_discount > thead > th {
  min-width: 100px;
  max-width: 200px;
  line-height: 36px;
  font-weight: inherit;
}
.card_discount > tbody > tr > td {
  text-align: center;
  border: 1px solid #ccc;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  height: 30px;
  line-height: 30px;
  font-size: 13px;
}
.card_discount > tbody > tr > td:nth-child(3) {
  cursor: pointer;
}
.card_discount > tbody td {
  background: #fff;
}
.search-box {
  position: relative;
}
</style>
<style>
.search-name .el-button--default {
  background: #ccc !important;
  border-top-left-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
  padding: 13px 20px !important;
}
.search-name .el-input__inner {
  border-top-right-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
}
.flex {
  display: flex;
  display: -webkit-flex;
  -webkit-align-items: center;
  align-items: center;
}
.flex1 {
  flex: 1;
  -webkit-flex: 1;
}
.search-add {
  width: 554px;
}
.search-add input {
  height: 36px;
  border: 1px solid #ccc;
  text-indent: 20px;
}
.search-add .el-button--default {
  background: #ccc;
  border-radius: 0;
}
</style>

